<!-- eslint-disable vue/html-indent -->
<template>
  <workDetail
    v-if="
      workDetailData.taskType === '加用户'
        ? showAppContent === '办事'
        : showAppContent === '办事' && PrimaryForms.length > 0
    "
    :workDetailData="workDetailData"
    :viewWorkType="viewWorkType"
    v-model:currentTabKey="currentTabKey"
    :workTask="workTask"
    :approverName="approverName"
    :instanceTaskInfo="instanceTaskInfo"
    :instanceInfo="instanceInfo"
    :remark="remark"
    :PrimaryForms="PrimaryForms"
    :DetailForms="DetailForms"
    @inputRemark="inputRemark"
    @curApproveTask="curApproveTask"
    @recallApply="recallApply"
  ></workDetail>
  <executorStr
    v-if="showAppContent === '字段变更'"
    :executor="Executor"
    @confirm="confirm"
  ></executorStr>
  <tm-modal
    title="请选择审批人"
    v-model:show="showWin"
    splitBtn
    :height="800"
    okText="确定"
    @ok="customOk"
  >
    <view v-for="(item, index) in nodeInfo" :key="index">
      <view>{{ item.name }}</view>
      <tm-tree
        ref="treeRef"
        :data="workCtrl.buildTree(item?.lookups || [])"
        :multiple="item.treeType === 'multiple' ? true : false"
        @check="(e:any)=>onCustomCheck(e,item.id,item.treeType)"
      >
      </tm-tree>
    </view>
  </tm-modal>
</template>

<script lang="ts" setup>
// #ifdef H5
import { useRoute } from 'vue-router'
// #endif
import { ref, getCurrentInstance, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import orgCtrl from '@/ts/controller'
import executorStr from '../work/components/content/executorStr.vue'
import workDetail from '../work/components/content/workDetail.vue'
import workCtrl from '../work/common'
import { model, schema } from '@/ts/base'
import { DetailType } from '../work/config'
import { CustomFormType } from '../work/workTypes'
import { TaskStatus } from '@/ts/core/public/enums'
import { WorkTask } from '../../ts/core/work/task'
import { AddNodeType } from '../../utils/work'
import { IExecutor } from '../../ts/core/work/executor'
import CustomWork from '../work/utils'
/** 当前选中tabkey */
const currentTabKey = ref<DetailType.PROCESS | DetailType.INFO>(DetailType.INFO)
/** 主表数据 */
const PrimaryForms = ref<CustomFormType[]>([])
/** 子表数据 */
const DetailForms = ref<CustomFormType[]>([])
/** 审批人名称 */
const approverName = ref<string>('')
/** 备注 */
const remark = ref<string>('')
/** 办事实例  */
const instanceInfo = ref<schema.XWorkInstance>()
/** 当前tabs页  */
const viewWorkType = ref<string>(uni.getStorageSync('taskType') || '待办')
/** 自由节点弹窗 */
const showWin = ref(false)
/** 审批人数据 */
const nodeInfo = ref<model.FieldModel[]>([])
/** 自由节点审批人数据 */
const gatewayData = new Map<string, string[]>()
const fromData = new Map<string, model.FormEditData>()
/** 审批任务流程数据 */
const workTask = ref<WorkTask>()
/** 执行器 */
const Executor = ref<IExecutor>()
/** 展示内容 */
const showAppContent = ref<string>('办事')
/** 流程实例展示数据 */
const instanceTaskInfo = ref<any>(undefined)
/** 办事详情数据 */
const workDetailData = ref<any>(null)
const treeRef = ref<any>(null)

onLoad(() => {
  uni.showLoading({
    title: '加载中...'
  })
  const instance: any = getCurrentInstance()?.proxy
  const eventChannel = instance.getOpenerEventChannel()
  eventChannel.on('workDetail', async function (data: any[]) {
    if(data[0].id && data[0].title){
      let task = new WorkTask(data[0], orgCtrl.provider)
      if (data[0].taskType === '加用户') {
        uni.hideLoading()
      }
      await task.loadInstance()
      await task.loadWorkNode()
      workTask.value = task
      loadInstanceInfo(data[0].instanceId, data[0].shareId, data[0].belongId)
      workDetailData.value = data[0]
    }else if(data[0].id && data[0].type==='已发起' && !data[0].title){
      const newData = await CustomWork.loadInfoTask('已发起',data[0].id)
      if(newData){
        let task = new WorkTask(newData, orgCtrl.provider)
        if (newData.taskType === '加用户') {
          uni.hideLoading()
        }
        await task.loadInstance()
        await task.loadWorkNode()
        workTask.value = task
        loadInstanceInfo(newData.instanceId, newData.shareId, newData.belongId)
        workDetailData.value = newData
      }
    }else if(data[0].id && data[0].type==='已完结' && !data[0].title){
      const newData = await CustomWork.loadInfoTask('已完结',data[0].id)
      if(newData){
        let task = new WorkTask(newData, orgCtrl.provider)
        if (newData.taskType === '加用户') {
          uni.hideLoading()
        }
        await task.loadInstance()
        await task.loadWorkNode()
        workTask.value = task
        loadInstanceInfo(newData.instanceId, newData.shareId, newData.belongId)
        workDetailData.value = newData
      }
    }
  })
})

/** 获取办事明细 */
async function loadInstanceInfo(
  instanceId: string,
  shareId: string,
  belongId: string
) {
  const res: schema.XWorkInstance | undefined =
    await orgCtrl.work.loadInstanceDetail(instanceId, shareId, belongId)
  if (res && res.data) {
    instanceInfo.value = res
    if (res.tasks!.length > 0) {
      instanceTaskInfo.value = res.tasks![0].records
    }
    loadApprover(res.createUser)
    makeWorkForms(JSON.parse(res.data))
    uni.hideLoading()
  }
}

/** 整理表单数据 */
function makeWorkForms(workData: model.InstanceDataModel): void {
  const node = workData.node
  const fields = workData.fields
  const data = workData.data
  const formNames = [...node.primaryForms, ...node.detailForms].map(v => {
    return { id: v.id, name: v.name }
  })
  node.forms.forEach(formItem => {
    if (data[formItem.id]) {
      const _fdata = {
        id: formItem.id,
        name: formNames.find(fm => fm.id === formItem.id)?.name ?? '',
        fields: fields[formItem.id],
        data: data[formItem.id]
      }
      switch (formItem.typeName) {
        case '主表':
          PrimaryForms.value = [...PrimaryForms.value, _fdata]
          break
        case '子表':
          DetailForms.value = [...DetailForms.value, _fdata]
          break
        default:
          break
      }
    }
  })
  uni.hideLoading()
}

/** 加载审批人 */
const loadApprover = async (id: string) => {
  try {
    const user = await workCtrl.findWorkEntityAsync(id)
    if (user) {
      approverName.value = user.name
    }
  } catch (error) {
    approverName.value = '未知'
  }
}

// 通过/拒绝
async function curApproveTask(
  status: number,
  backId: string,
  isAgree: boolean
) {
  if (workTask.value) {
    if (isAgree) {
      // 通过的操作
      const executor = (await workTask.value.loadExecutors()).find(
        item =>
          item.metadata.funcName === '字段变更' ||
          item.metadata.funcName === '任务状态变更'
      )
      if (executor) {
        Executor.value = executor
        showAppContent.value = executor.metadata.funcName
        return
      }
      await approving()
    } else {
      // 退回的操作
      uni.showLoading({
        title: '提交中,请稍后...'
      })
      approvalTask(status, remark.value, backId, isAgree)
    }
  }
}

const approving = async () => {
  if (workTask.value) {
    if (
      ['事项'].includes(workTask.value.taskdata.taskType) &&
      workTask.value.taskdata.approveType !== '抄送'
    ) {
      const res = await workTask.value.loadNextNodes()
      if (res.success) {
        if (res.data?.result) {
          const customNodes = res.data.result.filter(a =>
            [AddNodeType.CUSTOM, AddNodeType.Confluence].includes(
              a.nodeType as AddNodeType
            )
          )
          if (customNodes.length > 0) {
            uni.showLoading({
              title: '审批节点加载中...'
            })
            workCtrl.loadContent(workTask.value!.belong).then(() => {
              uni.hideLoading()
              showWin.value = true
              nodeInfo.value = customNodes.map(a =>
                workCtrl.convertToFields(a, workTask.value!.belong)
              )
              setTimeout(() => {
                if (treeRef.value) {
                  treeRef.value[0].expandAll()
                }
              }, 300)
            })
            return
          }
        }
      } else {
        uni.showToast({
          title: '查询下一节点异常!',
          icon: 'none'
        })
        return
      }
    }
    uni.showLoading({
      title: '提交中,请稍后...'
    })
    await approvalTask(
      TaskStatus.ApprovalStart,
      remark.value === '' ? '同意' : remark.value
    )
  }
}

// 撤回
const recallApply = async () => {
  if (workTask.value) {
    workTask.value.recallApply()
    uni.reLaunch({
      url:
        '/pages/work/work?code=' +
        model.TabItemsInfo.todo.code +
        '&label=' +
        model.TabItemsInfo.todo.label
    })
  }
}

// 自由审批节点选择
const onCustomCheck = (e: any, id: string, treeType: 'single' | 'multiple') => {
  if (treeType === 'single') {
    gatewayData.clear()
  }
  const oldData = gatewayData.get(id) || []
  const newData = [...oldData, e.data.id]
  gatewayData.set(id, newData)
}

/** 审批确认 */
const customOk = async () => {
  showWin.value = false
  uni.showLoading({
    title: '提交中,请稍后...'
  })
  await approvalTask(
    TaskStatus.ApprovalStart,
    remark.value === '' ? '同意' : remark.value
  )
}

/** 最终审批提交 */
const approvalTask = async (
  status: number,
  comment: string,
  backId?: string,
  isSkip?: boolean
) => {
  if (workTask.value) {
    await workTask.value.approvalTask(
      status,
      comment,
      fromData,
      gatewayData,
      backId,
      isSkip
    )
    uni.hideLoading()
    uni.showToast({
      title: '提交成功'
    })
    uni.reLaunch({
      url:
        '/pages/work/work?code=' +
        model.TabItemsInfo.todo.code +
        '&label=' +
        model.TabItemsInfo.todo.label
    })
  }
}

/** 执行器确认 */
const confirm = async () => {
  if (Executor.value) {
    await Executor.value.execute(fromData ?? new Map())
    await approving()
  }
}

/** 备注输入 */
const inputRemark = (e: string) => {
  remark.value = e
}

// #ifdef H5
onMounted(() => {
  const route = useRoute()
  const instance = getCurrentInstance()
  const queue = instance?.appContext.config.globalProperties.$queue
  if (queue) {
    queue.push({
      id: route.meta.id,
      title: route.meta.title,
      path: route.path
    })
  }
})
// #endif
</script>

<style lang="scss" scoped>
.mr32 {
  margin-right: 32px;
}
.mg10 {
  margin: 10px;
}
.apply-title {
  padding: 10px 0 10px 5px;
  border-bottom: 1px dashed #ddd;
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: bold;
  &::before {
    content: '';
    display: flex;
    width: 4px;
    height: 16px;
    background: #366ef4;
    margin-right: 8px;
  }
}
.apply-item {
  .flex-sub {
    flex: 1;
    text-align: end;
  }
  .gray {
    color: #6f7686;
  }
}
</style>
